// data_parse.js
// 格式化数据
var QUESTION_SPLITE = '__'; // 问题分隔
var ANSWER_SPLITE = '__'; // 答案分隔
var RICHTEXT_SPLITE = '__'; // 富文本分隔 四个下划线
/*
    格式化问题数据
*/
function formateQAData(sender) {
    var data = deepCopy(sender);
    for(var i = 0; i < data.length; i ++) {
        var item = data[i];
        // doStatus: 0 未做 1 正确 2 错误
        // canChange: 0 不可以修改 1 可以修改
        item.doStatus = 0;
        item.canChange = 1;

        item.relationId = item.id;
        item.scoreValue = '-1';
        item.fillAnswerStr = '';
        item.otherInfo = '';
        item.words = (item.questionWord || '') + '';
        var isReadOnly = item.questionTypeCode != 45 && item.questionTypeCode != 44;
        item.question = insertQuestionInput(item.words, i, isReadOnly);
        if(item.questionTypeCode == '51' && item.stuAnswerResultDetailScoreValue) {
            item.doStatus = 1;
        }

        // switch(item.questionTypeCode+'') {
        //     case '1': // 单词拼写
        //     case '2': // 单词分类
        //     case '3': // 翻译为中文
        //     case '9': // 英汉互译
        //     case '7': // 句型转换
        //     case '11': // 回答问题
        //         item.question = formateStrQuestion(item.words);
        //         item.answer = formateStrAnswer(item.answerStr);
        //         break;
        //     case '19': // 看动画片
        //     case '25': // 听句子排序
        //     case '4': // 听音排序
        //     case '5': // 单词排序
        //     case '12': // 听音选图
        //     case '13': // 看词选图
        //     case '14': // 看图选词
        //         break;
        //     case '22': // 完形填空
        //         item.question = formateRichtextQestion(item.questionWord, i);
        //         break;
        // }
        data[i] = item;
    }
    return data;
}

/**
 * [插入问题input]
 * @Author ljliu    2020-02-15T15:43:21+0800
 * @return {String} 替换完的字符串
 */
function insertQuestionInput(sender, index, isReadOnly, answer) {
    sender = sender || '';
    var inputStr = '<input type="text"', className = 'questionValue-'+ index;
    if(isReadOnly) {
        inputStr += ' readonly';
    }
    var result = '';
    inputStr += ' class="'+ className +'"';

    if(answer) {
        var answers = [], question = sender.split('__');
        className += answer.right ? ' right' : '';
        if(answer.right) {
            answers = answer.answer.split('__');
        }else {
            answers = answer.answer.split(';-;')
        }
        for (var i = 0; i < question.length-1; i++) {
            var item = question[i];
            var temp = inputStr +'';
            temp += ' value="'+ (answers[i] || '') +'"';
            temp += ' >';
            result += item + temp;
        }
    }else {
        inputStr += ' >';
        result = sender.replace(/__/g, inputStr);
    }

    result = result.replace(/\r\n|\n/g, '<br>');
    return result;
}

/*
    格式化题目
*/
// 字符串
function formateStrQuestion(sender) {
    var data = deepCopy(sender);
    var list = strSplite(data, QUESTION_SPLITE); // data.split(QUESTION_SPLITE);
    var last_is_q = true, q_index = 0;
    var result = [], _item = {isQ: false, word: '', index: -1};
    for(var i = 0;i < list.length;i ++) {
        var item = list[i];
        if(!last_is_q || (item == '' && i == 0)) {
            var temp = deepCopy(_item);
            temp.isQ = true;
            temp.index = q_index;
            q_index ++;
            last_is_q = true;
            result.push(temp);
        }else {
            last_is_q = false;
        }
        if(item != '') {
            var temp = deepCopy(_item);
            temp.word = item;
            last_is_q = false;
            result.push(temp);
        }
    }
    return result;
};
// str 字符串， s  分隔符
function strSplite(str, s) {
    var sLen = s.length, last = 0;
    var result = [];
    for(var i = 0; i < str.length; i ++) {
        var char = str[i];
        if(s.indexOf(char) != -1) {
            if(s == str.substr(i, sLen)) {
                if(i != 0 && last != i) {
                    result.push(str.substr(last, i - last));
                }
                result.push('');
                i += sLen -1;
                last = i +1;
            }
        }else if(i == str.length -1) {
            result.push(str.substr(last, i - last +1));
        }
    }
    return result;
}
// 富文本
function richInsertStr(index, _index) {
    // placeholder="请选择"
    var str = '<span class="fill-empty-input-box"><span data-flex="dir:left box:last cross:center">';
        str +=     '<input id="rich_input_'+ index +'_'+ _index +'" readonly type="text">';
        str +=     '<img id="rich_clear_'+ index +'_'+ _index +'" onclick="handleClearFillEmpty(\''+ index +'\',\''+ _index +'\')" src="./image/question/clear.png" alt="">';
        str +='</span></span>';
    return str;
}
function formateRichtextQestion(sender, index) {
    var data = deepCopy(sender);
    var list = data.split(RICHTEXT_SPLITE);
    var last_is_q = true, q_index = 0;
    var result = '';
    for(var i = 0;i < list.length;i ++) {
        var item = list[i];
        if(!last_is_q || (item == '' && i == 0)) {
            var temp = richInsertStr(q_index, index);
            q_index ++;
            last_is_q = true;
            result += temp;
        }else {
            last_is_q = false;
        }
        if(item != '') {
            last_is_q = false;
            result += item;
        }
    }
    return result;
}

/*
    格式化答案
*/
// 字符串
function formateStrAnswer(sender) {
    var data = deepCopy(sender);
    data = data.replace(/\s/g, '');
    data = data.split(ANSWER_SPLITE);
    data = cleanEmpty(data);
    return data;
}

// 连线题连线
function lineLeftToRight(id1, id2, isRight) {
    var line_dom = $api.byId(id1 + '_line'),
        _left = document.getElementById(id1),
        _right = document.getElementById(id2);
    var p_left = [_left.offsetLeft+_left.offsetWidth + 7, _left.offsetTop+_left.offsetHeight/2 -2],
        p_right = [_right.offsetLeft - 7, _right.offsetTop+_right.offsetHeight/2];
    var line_w = Math.sqrt(Math.pow(p_right[0] -p_left[0], 2)+Math.pow(p_right[1] -p_left[1], 2));
    // 位置
    var p_style = 'top:'+ p_left[1] +'px;left:'+ p_left[0] +'px;width:'+ line_w +'px;';
    if(isRight === 'error') {
        p_style += 'background-color: #808080;';
    }else if(isRight === true) {
        // 正确
        p_style += 'background-color: #01B8AC;';
    }else {
        p_style += 'background-color: #00649E;';
    }
    $api.css(line_dom, p_style);

    // 角度
    var cos = (p_right[0] -p_left[0])/line_w;
    var radina = Math.acos(cos); //用反三角函数求弧度
    var angle = Math.floor(180/(Math.PI/radina)); //将弧度转换成角度
    if(p_right[1] < p_left[1]) {
        angle *= -1;
    }
    $api.css(line_dom, 'transform: rotate('+ angle +'deg);');
}

// 简单深拷贝
function deepCopy(sender) {
    var result;
    if(typeof sender === 'object') {
        result = JSON.parse(JSON.stringify(sender));
    }else if(typeof sender === 'string') {
        result = sender + '';
    }else {
        result = sender;
    }
    return result;
}

// 去除空项
function cleanEmpty(sender) {
    var temp = deepCopy(sender || []);
    var data = [];
    for(var i = 0; i < temp.length; i ++) {
        var item = temp[i];
        if(item !== null && item !== undefined && item !== '') {
            data.push(item);
        }
    }
    return data;
}
// 第一个空项位置
function getFirstEmptyIndex(sender) {
    var temp = deepCopy(sender || []);
    var index = -1;
    for(var i = 0; i < temp.length; i ++) {
        var item = temp[i];
        if(item === null || item === undefined || item === '') {
            index = i;
            break
        }
    }
    return index;
}

// 给listmap批量设置属性值
function setPropertyInArray(array, key, value) {
    array = deepCopy(array || []);
    if(key) {
        value = value !== undefined ? value : '';
        for (var i = array.length - 1; i >= 0; i--) {
            array[i][key] = value;
        }
    }
    return array;
}

// 获取某个值的item
function getItemInArray(array, key, value) {
    var result = {};
    array = deepCopy(array || []);
    if(key) {
        value = value !== undefined ? value : '';
        for (var i = array.length - 1; i >= 0; i--) {
            if(array[i][key] == value) {
                result = array[i];
                break;
            }
        }
    }
    return result;
}

// 一套题是否提交
function isSubmiteQuestionList(list) {
    console.log(JSON.stringify(list));
    var result = true;
    if(!list.length) result = false;
    for(var i = 0; i < list.length; i ++) {
        var item = list[i];
        if(item.doStatus == 0) {
            result = false;
            break;
        }
    }
    return result;
}

// 一套题中未做的题目索引
function fnGetNotAnswerCountInList(list) {
    console.log(JSON.stringify(list));
    var result = [];
    if(!list.length) result = 0;
    for(var i = 0; i < list.length; i ++) {
        var item = list[i];
        if(item.doStatus == 0) {
            result.push(i);
        }
    }
    return result;
}

// 获取选项的大写字母
function getChar(val) {
    return String.fromCharCode(64 + parseInt(val * 1 + 1))
}
// 题库获取答题结果
function getFilleAnswer(item, index) {
    var result = '';
    var line_all = true, line_map = {}, i = 0, item1 = null;
    item.questionTypeCode = item.questionTypeCode+'';
    switch(item.questionTypeCode) {
        case '44': // listening
        case '45': // writing
            result = getInputValue($('.questionValue-'+index));
            break;
        case '46': // yes or no
        case '48': // Read.Choose
        case '53': // 绘本-单词题
        case '54': // 绘本-阅读理解
            if(item.sel !== undefined) {
                result = item.optionList[item.sel].optionId;
            }
            break;
        case '47': // Read.Drag
            line_map = [];
            for (i = 0; i < item.optionList.length; i++) {
                item1 = item.optionList[i];
                if(item1.sortIndex !== undefined) {
                    line_map.push(item.optionList[item1.sortIndex].optionId);
                }
            }
            if(line_map.length == item.optionList.length) {
                result = line_map.join(';-;');
            }
            break;
        case '49': // Read.Match
            line_map = {};
            console.log(JSON.stringify(item));
            for (i = 0; i < item.optionList1.length; i++) {
                item1 = item.optionList1[i];
                if (item1.lineRight) {
                    line_map[item1.optionId] = item.optionList2[item1.lineRight.replace('right_', '')].optionId;
                } else {
                    line_all = false;
                    break;
                }
            }
            if(line_all) result = JSON.stringify(line_map);
            break;
    }
    return result;
}

function getInputValue(list, join) {
    join = join || ';-;';
    var result = [];
    for (var i = 0; i < list.length; i++) {
        var item = list[i];
        if(item.value) {
            result.push(item.value);
        }else {
            return '';
        }
    }
    return result.join(join);
}
